﻿using System;
using Reactor.Environment;
using Reactor.Messages.Commands.Core;
using Reactor.Messaging;
using Reactor.Messaging.Attributes;
using Reactor.ServiceGrid;

namespace Reactor.CoreHost.Handlers
{
    [PointToPointChannel]
    public class RestartServiceCommandHandler : MessageHandlerBase<RestartService>
    {
        #region Overrides of MessageHandlerBase<RestartService>

        public override void OnHandling(RestartService message, IMessageContext messageContext)
        {
            AssertThatCurrentServiceIsAReactorCore();

            if (message.CoreName != Context.GridContext.CurrentReactorService.Identifier.Name) return;

            var core = (IReactorCore)Context.GridContext.CurrentReactorService;

            try
            {
                // Ensure message is for this Core
                if (message.CoreName != core.Identifier.Name)
                {
                    Log.WarnFormat("Received RestartService command but cannot process it because it was destined for another Core named: {0}", message.CoreName);
                    return;
                }

                core.RestartService(new ServiceIdentifier
                {
                    Name = message.ServiceName,
                    Version = new Version(message.ServiceVersion)
                });
            }
            catch (InvalidOperationException e)
            {
                Log.Error("ReactorCore threw an exception when RestartService was called.", e);
            }
        }

        #endregion
    }
}
